package com.library.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.library.bean.Book;
import com.library.dao.BaseDao;
import com.library.dao.BookDao;



public class BookDaoImpl implements BookDao{

	@Override
	public List<Book> selectAll(int pageNum,int pageSize) {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		List<Book> books = new ArrayList();
		String sql = "SELECT * FROM book LIMIT ?,?";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setInt(1,(pageNum-1)*pageSize);
			ps.setInt(2, pageSize);
			res = ps.executeQuery();
			while(res.next()) {
				Book book = new Book();
				book.setBookId(res.getInt("bookId"));
				book.setBookNo(res.getString("bookNo"));
				book.setBookName(res.getString("bookName"));
				book.setBookWriter(res.getString("bookWriter"));
				book.setBookPrice(res.getDouble("bookPrice"));
				book.setBookNum(res.getInt("bookNum"));
				book.setBookType(res.getString("bookType"));
				
				books.add(book);
			}
		}catch (SQLException e) {
			e.printStackTrace();
		}finally {
			BaseDao.closeAll(con, ps, res);
		}
		return books;
	}

	@Override
	public int selectAllBookNums() {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		int rows = 0;
		String sql = "SELECT count(1) as total FROM book";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			res = ps.executeQuery();
			if(res.next()) {
				rows = res.getInt("total");
			}
		}catch (SQLException e) {
			e.printStackTrace();
		}finally {
			BaseDao.closeAll(con, ps, res);
		}
		return rows;
	}

	@Override
	public int deleteBookById(int bookId) {
		Connection con = null;
		PreparedStatement ps = null;
		int result = 0;
		String sql = "DELETE FROM book WHERE bookId = ?";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setInt(1,bookId);
			result =ps.executeUpdate();
		}catch (SQLException e) {
			e.printStackTrace();
		}finally {
			BaseDao.closeAll(con, ps, null);
		}
		return result;
	}

	
}
